package com.zjyd.douyangsystem.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.zjyd.douyangcommoncore.entity.DyNews;
import com.zjyd.douyangcommoncore.result.Result;
import com.zjyd.douyangcommoncore.service.DyNewsService;
import com.zjyd.douyangcommoncore.utils.RocketMQSimpleHelper;
import com.zjyd.douyangcommoncore.vo.DyNewsVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 新闻相关接口
 */
@Slf4j
@RestController
@Tag(name = "新闻相关")
@RequestMapping("/douyang/system/news")
public class NewsController {

    @Autowired
    private DyNewsService dyNewsService;

    // 第三方学不懂怎么办？
    @Autowired
    private RocketMQSimpleHelper rocketMQSimpleHelper;

    /**
     * 添加新闻
     */
     @SentinelResource(
            value = "addNews",
            blockHandler = "demoBlockHandler",
            fallback = "demoFallback"
    )
    @Operation(summary = "添加新闻")
    @PostMapping("/add")
    public Result addNews(@RequestBody DyNewsVO dyNewsVO){
        DyNews dyNews = new DyNews();
        BeanUtil.copyProperties(dyNewsVO,dyNews);
        dyNewsService.save(dyNews);
        // 给MQ发送一个信息
        SendResult sendResult = rocketMQSimpleHelper.syncSend("news-wj-topic", dyNews);
        log.info("消息发送成功，msgId：{}", sendResult.getMsgId());

        return Result.success();
    }
      public static Result demoBlockHandler(DyNewsVO dyNewsVO, BlockException e){
        return Result.error("系统繁忙稍后搞,流量降级触发了");
    }
    @SentinelResource(
            value = "test1",
            blockHandler = "demoBlockHandler", //熔断执行
            fallback = "demoFallback" //异常执行
    )
    @Operation(summary = "添加东西")
    @PostMapping("/add1")
    public Result test1(){
        double random =Math.random();
        if (random<0.5){
            throw new RuntimeException("触发异常");
        }
        return Result.success("添加成功");
    }


    public static Result demoFallback(Throwable e){
        return Result.error("添加新闻异常");
    }
    public static Result demoBlockHandler( BlockException e){
        return Result.error("熔断了");
    }
}
